const loveModel = require('../db/love')
const shopModel = require('../db/shoplist')
const {resinfo} = require('../utils/utils')
const AlipaySdk = require('alipay-sdk').default
const AlipayFormData = require("alipay-sdk/lib/form").default;
module.exports = {
    lovaAdd: async (req,res)=>{
        let resobj = {
            Code:0,
            msg:'添加藏品成功',
        }
        // 请求头检查是否携带了令牌 - 验证令牌是否有效
        // 从请求头获取令牌 - 传递使用大写，到了服务器就成小写了
        // 给购物车表中添加数据 - 传递过来数据 - 获取数据
        let {shopId,userId,shopNum,userName} = req.body
        if(!shopId||!userId||!shopNum||!userName){
            resobj.Code = 1,
            resobj.msg = '参数缺失',
            res.json(resobj)
        }else{
            //根据商品id和用户id查询是否有数据
            let data = await loveModel.find({
                shopId,
                userId
            })
            //判断是否查询到
            if (data.length) {
                resobj.Code = 2,
                resobj.msg = '添加失败',
                res.json(resobj)
                //修改数量
                // let updataResult = await loveModel.updateOne({
                //     shopId,
                //     userId
                // },{$set:{
                //     shopNum:+data[0].shopNum + +shopNum
                // }})
                //判断结果
                // if(updataResult){
                //     res.json(resobj)
                // }else{
                //     resobj.Code = 2,
                //     resobj.msg = '添加失败',
                //     res.json(resobj)
                // }
            } else {
                await shopModel.updateOne({ _id: shopId }, {
                    $set: {
                        selled: userName
                    }
                })
                //添加到数据库
                let interResult = await loveModel.insertMany({
                    shopId,
                    userId,
                    shopNum
                })
                //判断
                if(interResult.length){
                    res.json(resobj)
                }else{
                    resobj.Code = 2,
                    resobj.msg = '添加失败',
                    res.json(resobj)
                }
            }
        }
    },
    //获取藏品数据列表
    loveList:async (req,res)=>{
        let {id} = req.params
        let loveData
        try {
            loveData = await loveModel.find({
                userId:id
            })
        } catch (error) {
            resinfo(res,1,'获取藏品数据失败')
            return
        }
        if(loveData.length){
            resinfo(res,0,'获取藏品数据成功',loveData)
        }else{
            resinfo(res,1,'获取藏品数据失败')
        }
    },
    //删除单个藏品列表
    loveRemove: async (req,res)=>{
        let {userId,shopId,shopPrice} = req.body
        try {
            await shopModel.updateOne({ _id: shopId }, {
                $set: {
                    selled: 'selling',
                    shopPrice: `￥${shopPrice}`
                }
            })
            await loveModel.deleteOne({
                userId,
                shopId
            })
            resinfo(res,0,'转售成功')
        }catch(err){
            resinfo(req,1,'转售失败')
        }
    },
    //用户支付(不知道为什么一直报错，该接口使用作废)
    lovaPay: async(req,res)=>{
        
        const alipaySdk =  new AlipaySdk({
            appId:'2021000121692356',// 开放平台上创建应用时生成的 appId
            signType: 'RSA2',// 签名算法,默认 RSA2
            gateway: 'https://openapi.alipaydev.com/gateway.do',// 支付宝网关地址
            alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApn4NV7pl0LvMDPARvUelFVKBET8IgZPdMCSFcct/mgnUwDAb59VkrlY3MK7MyPz7egCF/FW6KoJOPfBkFws/YFrZKB97B3A6lrryJ5nzOP9CcOqUvgUdNzLtOSOLfhN3YhXPJAHS001MpVFGzRrAt53M+jNMEVsjK9uEiipW0vkN/wlf+HQmriDD990D8gS89n+l4Sn/oY9fse5S0uVWrUZ5qF0b17h8fm2yygtUCFFipAwg9YLykKalGKpgFNUnCRiDMsZsQQacTOkmo9cMRVompgq1dHCGvwqZKslsrpdocoZAhit7yHic/wLP7kXvjCP8+Qz0uyjecbPouVfZZQIDAQAB',//支付宝公钥
            privateKey:'MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQC3De8Qo+oO+0k+IpEJdJVJH2F0jvv9DRobyAQ/UTp6TDnppxZTaIohU+V6GjBgEmTlNJG3jOz3UDaf/f6PcroSKvFqQRy71YOyKnIYQpZTK1HmIPsG05MUYa/e+XPuCSz6uRqaIq8c36nDKfBpuaAs+11JD9MyFU4p778VdvBrnGjAOgu6qExh6y6zToww+vQJsLLwuCLYmjj5KnWeUc534xvPwqzQPfkKnf37AZUaqIdMiepC/kEuc0BmiircXiym3+mJWCUN/NitgI3e6ntu6jrAFLn28sjubtxdUT5qy+NXmePESM4eNS9Aaoy1xvf8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W3LYK0Rhx7iUCgYEArjHHrZY4Un4W7fhwrDZU+xO0obCDyxtpRXAfu8UcD7dkxaUthG/uR4velqJvMHrP8GGUmqvX2IWIB5R+VOI1mYjoTZH/1kHaxT3tkjzswfXVsh9wxUCkJAMdfUBQQWSYbSBEoGnf3YfO6fGQATwFiMZ+kxQh2tqer+hss0/6r4U='//应用私钥
        });
        const formData = new AlipayFormData();
        formData.setMethod('get');
         // 通过 addField 增加参数
        // 在用户支付完成之后，支付宝服务器会根据传入的 notify_url，以 POST 请求的形式将支付结果作为参数通知到商户系统。
        formData.addField('notifyUrl', 'https://star02.top');
        formData.addField('bizContent',{
            outTradeNo:Math.floor(Math.random()*1000000000000),// 商户订单号,64个字符以内、可包含字母、数字、下划线,且不能重复
            productCode: 'FAST_INSTANT_TRADE_PAY',// 销售产品码，与支付宝签约的产品码名称,仅支持FAST_INSTANT_TRADE_PAY
            totalAmount: '0.01',// 订单总金额，单位为元，精确到小数点后两位
            subject: '商品',// 订单标题
            body: '商品详情',// 订单描述
        });
        formData.addField('returnUrl', 'https://opendocs.alipay.com');//加在这里才有效果,不是加在bizContent 里面
        const result = alipaySdk.exec(  // result 为可以跳转到支付链接的 url
            'alipay.trade.page.pay', // 统一收单下单并支付页面接口
            {}, // api 请求的参数（包含“公共请求参数”和“业务参数”）
            { formData: formData },
        );
        result.then((resp)=>{
            res.send(
                {
                    "success": true,
                    "message": "success",
                    "code": 200,
                    "timestamp": (new Date()).getTime(),
                    "result": resp
                }
            )
        })
    }
}